package com.shao.loadBalance.impl;

import com.shao.exception.RoundRobinLoadSelectorException;
import com.shao.loadBalance.AbstractLoadBalancer;
import com.shao.loadBalance.Selector;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/5/6 14:48
 */
@Slf4j
public class RoundRobinLoadBalancer extends AbstractLoadBalancer {

    @Override
    protected Selector getSelector(List<InetSocketAddress> addresses) {
        return new RoundRobinLoadSelector(addresses);
    }

    @Data
    @Accessors(chain = true)
    private static class RoundRobinLoadSelector implements Selector {

        private List<InetSocketAddress> socketAddressesList;
        // 游标指针
        private final AtomicInteger index;

        public RoundRobinLoadSelector(List<InetSocketAddress> socketAddressesList) {
            this.socketAddressesList = socketAddressesList;
            this.index = new AtomicInteger(-1);
        }

        @Override
        public InetSocketAddress getNext() {
            if (socketAddressesList.isEmpty()) {
                log.error("轮询负载均衡为空");
                throw new RoundRobinLoadSelectorException();
            }
            index.incrementAndGet();
            if (index.get() >= socketAddressesList.size() || index.get() < 0) {
                index.set(0);
            }
            log.debug("使用轮询负载均衡获取下一个服务节点【{}】", socketAddressesList.get(index.get()));
            return socketAddressesList.get(index.get());
        }
    }
}
